package h0907.sort;

import java.util.Arrays;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 归并排序
 * @date 2024/9/7 19:57
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] nums = {5, 6, 1, 2, 3, 4};
        mergeSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    //分解，解决，合并
    private static void mergeSort(int[] nums) {
        if (nums.length > 1) {
            int mid = nums.length / 2;
            int[] left = Arrays.copyOfRange(nums, 0, mid);
            int[] right = Arrays.copyOfRange(nums, mid, nums.length);
            mergeSort(left);
            mergeSort(right);
            marge(nums, left, right);
        }
    }

    private static void marge(int[] nums, int[] left, int[] right) {
        int i = 0;
        int j = 0;
        int idx = 0;
        int m = left.length;
        int n = right.length;
        while (i < m && j < n) {
            if (left[i] <= right[j]) {
                nums[idx++] = left[i];
                i++;
            } else {
                nums[idx++] = right[j];
                j++;
            }
        }
        while (i < m) {
            nums[idx++] = left[i++];
        }
        while (j < n) {
            nums[idx++] = right[j++];
        }
    }

}
